// pages/edit/edit.js
const db = wx.cloud.database();
const addressCollection = db.collection('address');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {
      _id:'',
      name: '',
      phone: '',
      detail: ''
    },
    addressList: [],
  },

  /**
   *在 edit 页面的 onLoad 生命周期函数中获取传递过来的地址对象，并将其设置到 data 中
   */
  onLoad: function(options) {
    const address = {
      name: options.name,
      phone: options.phone,
      detail: options.detail,
      _id:options._id
    };
    this.setData({
      address: address // 将地址对象设置到 edit 页面的 data 中
    });
  },
  // 获取地址列表
  getAddressList() {
    addressCollection.get({
      success: res => {
        this.setData({
          addressList: res.data
        })
      },
      fail: err => {
        console.error('获取地址列表失败', err);
      }
    })
  },
    // 修改地址
    editAddress(address) {
      db.collection('address').doc(address._id).update({
        data: {   
          name:address.name,
          phone:address.phone,
          detail:address.detail,
        },
        success: res => {
          wx.showToast({         
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          this.getAddressList();
          wx.navigateBack();
        },
        fail: err => {
          console.error('修改失败', err);
        }
      })
    },
      // 提交表单
  formSubmit(e) {
    const address = e.detail.value;
    var eid=this.data.address._id;
    // console.log(eid);
    console.log(address);
    if (address.name && address.phone && address.detail) {
      if (eid) {
        // 更新地址
        address._id = eid;
        this.editAddress(address);
      } else {
        // 添加地址
        this.addAddress(address);
      }
      // wx.navigateBack();
    } else {
      wx.showModal({
        title: '提示',
        content: '请填写完整资料',
        showCancel: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  }
})